<template>
  <!-- 顶部标题栏 -->
  <PageHeader title="我的课程"/>
  <!-- tab栏 -->
  <view class="flex w-full bg-white sticky top-[100rpx] z-10">
    <view
        v-for="(tab, idx) in tabs"
        :key="tab"
        class="flex-1 text-center py-[24rpx] text-[30rpx] cursor-pointer transition-all"
        :class="[
        activeTab === idx
          ? 'text-blue-500 font-bold border-b-solid border-b-2 border-blue-500'
          : 'text-gray-500 font-normal border-b-solid border-b-2 border-gray-100'
      ]"
        @click="activeTab = idx; handleTabChange()"
    >
      {{ tab }}
    </view>
  </view>
  <!-- 内容区 -->
  <view class="p-[30rpx] min-h-[60vh]">
    <!-- 购买的课程列表 -->
    <view v-show="activeTab === 0">
      <template v-if="purchasedCourses.length">
        <view
            v-for="item in purchasedCourses"
            :key="item.id"
            class="bg-white rounded-2xl shadow-md p-[30rpx] mb-[24rpx] flex items-center gap-[24rpx] relative course-card"
            @tap="goDetail(item)"
        >
          <!-- 左侧课程信息 -->
          <view class="flex-1 min-w-0">
            <view class="course-name text-[32rpx] font-bold mb-[12rpx] line-clamp-2 min-h-[80rpx]">{{ item.name }}</view>

            <view class="flex items-center justify-between">
              <view class="course-price text-[#ff0000] text-[32rpx] font-bold">¥{{ item.price }}</view>
              <view class="course-duration text-[#666] text-[26rpx] mb-[8rpx]">时长: {{ formatDuration(item?.cycle) }}</view>
            </view>
           
          </view>
          <!-- 右侧封面图 -->
          <view class="flex-shrink-0">
            <image 
              :src="getImageSrc(item.cover)" 
              mode="aspectFit" 
              class="w-[150rpx] h-[120rpx] rounded-[12rpx] bg-gray-100 object-cover bigs"
            />
          </view>
         
        </view>
      </template>
      <view v-else class="text-center py-[100rpx] text-[#999] text-[28rpx]">暂无购买课程</view>
    </view>
    <!-- 发布的课程列表 -->
    <view v-show="activeTab === 1">
      <template v-if="publishedCourses.length">
        <view
            v-for="item in publishedCourses"
            :key="item.id"
            @tap="goRecorder(item)"
            class="bg-white rounded-2xl shadow-md p-[30rpx] mb-[24rpx] flex items-center gap-[24rpx] relative course-card"
        >
          <!-- 左侧课程信息 -->
          <view class="flex-1 min-w-0">
            <view class="course-name text-[32rpx] font-bold mb-[12rpx] line-clamp-2 min-h-[80rpx]">{{ item.name }}</view>

            <view class="flex items-center justify-between">
              <view class="course-price text-[#ff0000] text-[32rpx] font-bold">¥{{ item.price }}</view>
              <view class="course-duration text-[#666] text-[26rpx] mb-[8rpx]">时长: {{ formatDuration(item?.cycle) }}</view>
            </view>
           
          </view>
          <!-- 右侧封面图 -->
          <view class="flex-shrink-0">
            <image 
              :src="getImageSrc(item.cover)" 
              mode="aspectFit" 
              class="w-[150rpx] h-[120rpx] rounded-[12rpx] bg-gray-100 object-cover bigs"
            />
          </view>

           <!-- 状态标签 -->
           <view class="absolute top-0 right-0 bg-[#666] text-white rounded-bl-[12rpx] px-[8rpx] py-[4rpx]" v-if="item.status >= 5">
            <view class="text-[18rpx] text-[#fff]">
              {{ item.status == 5 ? '已取消' : '已结算' }}
            </view>
          </view>
        </view>
      </template>
      <view v-else class="text-center py-[100rpx] text-[#999] text-[28rpx]">暂无发布课程</view>
    </view>
  </view>
  
  <!-- 加载更多按钮 -->
  <view class="flex justify-center mt-[20rpx] mb-[30rpx]">
    <nut-button
      :loading="isLoading"
      :disabled="isLoading || !hasMore"
      @click="loadMore"
    >
      {{ !hasMore ? "没有更多了" : "加载更多" }}
    </nut-button>
  </view>
</template>

<script setup lang="ts">
import Taro, { useDidShow } from '@tarojs/taro'
import {ref, onMounted} from 'vue'
import PageHeader from '@/components/PageHeader.vue'
import {post, getFullPath} from "@/utils/request";
import {formatDuration} from "@/utils/comm";
// import { Button as nutButton } from "@nutui/nutui-taro";
// import {autoHandleReferralCode} from "@/utils/hack";
//import console from 'console';
// 默认图片路径
const defaultImage = "http://www.dzgktf.com/templets/default/images/wtyt.jpg";


const allCourses = ref()
const page = ref(1)
const pageSize = 6

// 分页相关变量
let hasMore = true; // 是否还有更多
let pageNo = 1; // 当前页码
const pageSizeValue = 10; // 每页数量
const isLoading = ref(false); // 加载中状态
const tabs = ['我购买的', '我发布的']
const activeTab = ref(0)
/**
 * 我的课程页面
 * @description 课程tab切换、列表展示，严格按设计稿和Cursor规则实现。
 * @performance 只渲染当前tab内容，列表用v-for+mock数据，移动端适配。
 */
const filteredCourses = ref([] as typeof allCourses.value)

// 重置分页参数
const resetPagination = () => {
  pageNo = 1;
  purchasedCourses.value = [];
  publishedCourses.value = [];
  hasMore = true;
};

// 加载更多
const loadMore = () => {
  if (isLoading.value || !hasMore) return;
  query();
};

// 处理tab切换
const handleTabChange = () => {
  resetPagination();
  query();
};

function query () {
  // 防止重复请求
  if (isLoading.value || !hasMore) {
    if (!hasMore) {
      Taro.showToast({ title: "没有更多了", icon: "none" });
    }
    return;
  }

  isLoading.value = true; // 开始加载

  //查询参数
  const submitparam = {
    pageNo: pageNo,
    pageSize: pageSizeValue
  }
  
  try {
    //获取购买的课程
    if (activeTab.value === 0) {
      post("/training/mySignUp", submitparam).then(res => {
        if (res.code === 0) {
          const newItems = res.data.map((item: CoursesItem) => ({
            payId: item.columns.payId,
            id: item.columns.id,
            name: item.columns.title,
            cover: item.columns.cover,
            cycle: item.columns.cycle,
            price: item.columns.price,
            payStatus: item.columns.pay_status,
            status: item.columns.status
          }));
          
          // 第一页直接赋值，后续页追加数据
          if (pageNo === 1) {
            purchasedCourses.value = newItems;
          } else {
            purchasedCourses.value = [...purchasedCourses.value, ...newItems];
          }
          
          // 判断是否还有更多数据
          if (newItems.length < pageSizeValue) {
            hasMore = false;
          } else {
            pageNo++; // 页码+1，下次加载下一页
          }
        } else {
          Taro.showToast({ title: res.msg || "加载失败", icon: "none" });
        }
        isLoading.value = false;
      }).catch(error => {
        console.error("获取购买课程失败：", error);
        Taro.showToast({ title: "加载失败", icon: "none" });
        isLoading.value = false;
      });
    }
    
    //获取发布的课程
    if (activeTab.value === 1) {
      post("/training/myRelease", submitparam).then(res => {
        if (res.code === 0) {
          const newItems = res.data.map((item: CoursesItem) => ({
            id: item.columns.id,
            name: item.columns.title,
            cover: item.columns.cover,
            cycle: item.columns.cycle,
            price: item.columns.price,
            payStatus: item.columns.pay_status,
            status: item.columns.status
          }));
          
          // 第一页直接赋值，后续页追加数据
          if (pageNo === 1) {
            publishedCourses.value = newItems;
          } else {
            publishedCourses.value = [...publishedCourses.value, ...newItems];
          }
          
          // 判断是否还有更多数据
          if (newItems.length < pageSizeValue) {
            hasMore = false;
          } else {
            pageNo++; // 页码+1，下次加载下一页
          }
        } else {
          Taro.showToast({ title: res.msg || "加载失败", icon: "none" });
        }
        isLoading.value = false;
      }).catch(error => {
        console.error("获取发布课程失败：", error);
        Taro.showToast({ title: "加载失败", icon: "none" });
        isLoading.value = false;
      });
    }
  } catch (error) {
    console.error("查询课程失败：", error);
    Taro.showToast({ title: "加载失败", icon: "none" });
    isLoading.value = false;
  }
}

interface submitParam {
  id: number,
  pageNo: number,
  pageSize: number,
  trainingId: number,
  payStatus: number,
  status: number
}

interface CoursesColumn {
  member_id:null,
  teachers_pic:null,
  sign_rate:null,
  teacher_name:null,
  member_number:null,
  teachers_introduction:null,
  create_time: number,
  pay_number:null,
  title:null,
  type:null,
  cycle_type:null,
  cycle:null,
  cover:null,
  update_time: null | number;
  pay_status:null,
  total_amount:null,
  price:null,
  progress:null,
  id: number,
  payId: number,
  introduction:null,
  status:number
}

interface CoursesItem {
  columns: CoursesColumn;
  columnNames: string[];
  columnValues: (null | number | string)[];
}

// 定义课程项类型
interface CourseItem {
  id: number;
  name: string;
  cover?: string;
  duration?: string;
  cycle?: number; // 添加cycle属性
  price: string;
  payStatus?: number;
  status?: number;
  payId?: number;
}

// mock数据
const purchasedCourses = ref<CourseItem[]>([])
const publishedCourses = ref<CourseItem[]>([])


const goDetail = (item: any) => {
  // Taro.navigateTo({url: `/pages/webs/training?id=${item.id}&payId=${item.payId}`})
  Taro.navigateTo({url: `/pages/course/detail?id=${item.id}&payId=${item.payId}`})
}

const goRecorder = (item: any) => {
  Taro.navigateTo({url: `/pages/course/recorder?id=${item.id}`})
}

/**
 * 处理图片加载错误
 */
const handleImageError = (e: any) => {
  console.log('图片加载失败:', e)
  // 设置默认图片
  e.target.src = defaultImage
}

/**
 * 获取图片源，如果为空则使用默认图片
 */
const getImageSrc = (cover: string | undefined) => {
  if (!cover) {
    return defaultImage
  }
  return getFullPath(cover)
}

onMounted(() => {
  query()
})

/**
 * 页面显示时刷新数据
 * @description 每次页面显示时都会重新加载数据，确保数据最新
 */
useDidShow(() => {
  console.log('页面显示，刷新数据')
  resetPagination()
  query()
})
</script>

<style scoped lang="scss">
/* 文本截断样式 */
.line-clamp-1 {
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
}

.line-clamp-2 {
  overflow: hidden;
  text-overflow: ellipsis;
  display: -webkit-box;
  -webkit-line-clamp: 2;
  -webkit-box-orient: vertical;
}

/* 课程卡片悬停效果 */
.course-card {
  transition: all 0.3s ease;
  
  &:hover {
    transform: translateY(-2rpx);
    box-shadow: 0 8rpx 24rpx rgba(0, 0, 0, 0.12);
  }
}
.bigs{
  :deep(img){
    width: 100%;
    height: 100%;
    object-fit: cover;
  }
}
</style>